<template>
  <div class="steps-map-card">
    <div class="card-title">各地区平均步数热力图</div>
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import { useDashboardStore } from '../stores/dashboard';
import chinaMap from '../assets/中华人民共和国.json';

const dashboardStore = useDashboardStore();
const chartContainer = ref(null);
let chart = null;

const initChart = () => {
  if (!chartContainer.value) return;
  chart = echarts.init(chartContainer.value);
  echarts.registerMap('china', chinaMap);
  updateChart();
  window.addEventListener('resize', () => {
    chart.resize();
  });
};

const updateChart = () => {
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}步/天'
    },
    visualMap: {
      min: 2000,
      max: 10000,
      left: 'left',
      top: 'bottom',
      text: ['高', '低'],
      // 使用红橙色系列
      inRange: {
        color: ['#ffffcc', '#ffeda0', '#fed976', '#feb24c', '#fd8d3c', '#fc4e2a', '#e31a1c', '#b10026']
      },
      calculable: true
    },
    series: [
      {
        name: '平均步数',
        type: 'map',
        map: 'china',
        roam: true,
        layoutCenter: ['50%', '55%'],
        layoutSize: '90%',
        label: { show: false },
        data: Array.isArray(dashboardStore.regionStepsData?.value) 
          ? dashboardStore.regionStepsData.value 
          : Array.isArray(dashboardStore.regionStepsData) 
            ? dashboardStore.regionStepsData 
            : []
      }
    ]
  };
  chart.setOption(option);
};

watch(
  () => Array.isArray(dashboardStore.regionStepsData?.value) 
    ? dashboardStore.regionStepsData.value 
    : dashboardStore.regionStepsData,
  (val) => {
    if (Array.isArray(val)) {
      val.forEach(item => {
        console.log(item.name, item.value);
      });
      if (chart) updateChart();
    } else {
      console.log('regionStepsData 不是数组', val);
    }
  },
  { immediate: true, deep: true }
);

onMounted(() => {
  initChart();
});
</script>

<style scoped>
.steps-map-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.card-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}
.chart-container {
  width: 100%;
  height: 480px;
  min-height: 400px;
  flex: 1;
}
</style>